package com.ziytek.web.citizen.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.model.bean.DbNameList;
import com.ziytek.web.citizen.model.rsp.QueryDbNameRsp;
import com.ziytek.web.citizen.service.itf.HistoryDbQueryService;
import com.ziytek.web.citizen.util.LocationUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @className HistoryDbQueryServiceImpl
 * @description: 历史数据库查询服务实现类
 * @jdkVersion: 1.8
 * @author: fhx
 * @date: 2024/7/2 9:53
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class HistoryDbQueryServiceImpl implements HistoryDbQueryService {
    @Override
    public QueryDbNameRsp queryAllDbName() {
        var rsp = new QueryDbNameRsp();
        rsp.error();
        var locationAddress = LocationUtils.getLocation();
        //log.info("当前项目数据库文件路径：{}", locationAddress);
        // 文件不存在
        var folder = new File(locationAddress + "/db");
        if (!folder.exists()) {
            log.info("文件夹[{}]不存在", locationAddress + "/db");
            rsp.setRetMsg(String.format("文件夹[%s]不存在", locationAddress + "/db"));
            return rsp;
        }

        List<DbNameList> dbNameLists = new ArrayList<>();
        if (folder.isDirectory()) {
            var files = folder.listFiles();
            if (files == null || files.length == 0) {
                return rsp;
            }

            for (var file : files) {
                if (!file.isDirectory()) {
                    continue;
                }

                var dbFiles = file.listFiles();
                if (dbFiles == null) {
                    continue;
                }

                var nameList = getDbNameList(dbFiles, file.getName());
                if (!CollectionUtils.isEmpty(nameList)) {
                    nameList.sort(Comparator.reverseOrder());
                    var one = new DbNameList();
                    one.setDateString(file.getName());
                    one.setTimeFormat(nameList);
                    dbNameLists.add(one);
                }
            }
        }

        if (!CollectionUtils.isEmpty(dbNameLists)) {
            dbNameLists.sort((o1, o2) -> o2.getDateString().compareTo(o1.getDateString()));
            rsp.setData(dbNameLists);
        }

        rsp.success();
        return rsp;
    }

    private List<String> getDbNameList(File[] dbFiles, String fileDate) {
        if (dbFiles == null || dbFiles.length == 0) {
            return Collections.emptyList();
        }

        List<String> nameList = new ArrayList<>();
        for (var dbFile : dbFiles) {
            if (!(dbFile.isFile() && dbFile.getName().endsWith(ServerConstant.DB_END_WITH))) {
                continue;
            }

            var dbName = dbFile.getName()
                    .replace(ServerConstant.DB_END_WITH, ServerConstant.STR_EMPTY)
                    .replace(ServerConstant.DB_START_WITH, ServerConstant.STR_EMPTY);
            if (StringUtils.isEmpty(dbName) || dbName.length() != NumConstant.INT_FORTY) {
                continue;
            }

            try {
                var date = DateUtils.parseDate(dbName, ServerConstant.DATE_FORMAT_TWO);
                var dateString = DateFormatUtils.format(date, ServerConstant.DATE_FORMAT_DAY_TWO);
                if (StringUtils.isEmpty(fileDate) || !fileDate.equals(dateString)) {
                    continue;
                }
                nameList.add(DateFormatUtils.format(date, ServerConstant.DATE_FORMAT_TIME));
            } catch (Exception ignored) {
            }
        }

        return nameList;
    }
}
